<template>
  <view class="order-list-page">
    <!-- 动态背景 -->
    <view class="particle-bg">
      <view class="particle p1"></view>
      <view class="particle p2"></view>
      <view class="particle p3"></view>
    </view>

    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <uni-icons type="arrowleft" size="28" color="#fff"></uni-icons>
      </view>
      <text class="nav-title">{{getStatusTitle(activeStatus)}}</text>
      <view class="nav-placeholder"></view>
    </view>

    <!-- 状态选项卡 -->
    <view class="status-tabs">
      <view 
        v-for="(tab, index) in tabs" 
        :key="index"
        class="tab-item"
        :class="{active: activeStatus === tab.status}"
        @click="switchStatus(tab.status)"
      >
        <view class="tab-icon">
          <uni-icons 
            :type="tab.icon" 
            size="28" 
            :color="activeStatus === tab.status ? getStatusColor(tab.status) : '#999'"
          ></uni-icons>
        </view>
        <text :style="{color: activeStatus === tab.status ? getStatusColor(tab.status) : '#999'}">
          {{tab.name}}
        </text>
        <view 
          class="tab-badge" 
          v-if="getOrderCount(tab.status) > 0"
          :style="{backgroundColor: getStatusColor(tab.status)}"
        >
          {{getOrderCount(tab.status)}}
        </view>
      </view>
    </view>

    <!-- 订单列表 -->
    <scroll-view 
      class="order-container" 
      scroll-y
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 空状态 -->
      <view class="empty-state" v-if="filteredOrders.length === 0">
        <image class="empty-icon" src="/static/empty-order.png"></image>
        <text class="empty-text">暂无{{getStatusTitle(activeStatus)}}订单</text>
        <text class="empty-tip">下拉刷新获取最新订单</text>
      </view>

      <!-- 订单列表 -->
      <view 
        class="order-card" 
        v-for="(order, index) in filteredOrders" 
        :key="order.id"
        :style="{animationDelay: `${index * 0.1}s`}"
        @click="viewOrderDetail(order.id)"
      >
        <view class="order-header">
          <text class="order-no">订单编号：DD{{order.id.toString().padStart(6, '0')}}</text>
          <view class="order-status" :style="{backgroundColor: getStatusBgColor(order.status)}">
            <text :style="{color: getStatusColor(order.status)}">{{getStatusText(order.status)}}</text>
          </view>
        </view>

        <view class="order-content">
			<view class="info-row">
			  <uni-icons type="star" size="24" color="#FF9800"></uni-icons>
			  <text class="info-text">取件码：{{order.pickupCode}}</text>
			</view>
          <view class="info-row">
            <uni-icons type="location" size="24" color="#FF9800"></uni-icons>
            <text class="info-text">取件地点：{{order.pickupLocation}}</text>
          </view>
          <view class="info-row">
            <uni-icons type="home" size="24" color="#4CAF50"></uni-icons>
            <text class="info-text">收件人：{{order.villagerName}} ({{order.villagerPhone}})</text>
          </view>
		  <!-- <view class="info-row">
		    <uni-icons type="home" size="24" color="#4CAF50"></uni-icons>
		    <text class="info-text">家庭住址：{{order.address}}</text>
		  </view> -->
          <view class="info-row">
            <uni-icons type="calendar" size="24" color="#2196F3"></uni-icons>
            <text class="info-text">下单时间：{{formatTime(order.createTime)}}</text>
          </view>
          <view class="info-row" v-if="order.itemRemarks">
            <uni-icons type="compose" size="24" color="#9C27B0"></uni-icons>
            <text class="info-text">{{order.itemRemarks}}</text>
          </view>
        </view>

        <view class="order-footer">
          <text class="order-price">¥{{order.finalPrice.toFixed(2)}}</text>
          <view class="order-actions">
            <button 
              class="action-btn" 
              v-if="order.status === 0"
              @click.stop="acceptOrder(order.id)"
              :style="{backgroundColor: getStatusColor(0)}"
            >
              接单
            </button>
            <button 
              class="action-btn" 
              v-if="order.status === 1"
              @click.stop="pickupOrder(order.id,order.address)"
              :style="{backgroundColor: getStatusColor(1)}"
            >
              取件
            </button>
            <button 
              class="action-btn" 
              v-if="order.status === 2"
              @click.stop="completeOrder(order.id)"
              :style="{backgroundColor: getStatusColor(2)}"
            >
              完成
            </button>
          </view>
        </view>

        <view class="order-wave" :style="{background: getWaveColor(order.status)}"></view>
      </view>
    </scroll-view>

    <!-- 浮动操作按钮 -->
    <view class="float-btn" @click="scanQRCode">
      <uni-icons type="scan" size="32" color="#fff"></uni-icons>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeStatus: 0, // 0:待接单 1:已接单 2:配送中 3:已完成
      refreshing: false,
      tabs: [
        { name: '待接单', icon: 'cart', status: 0 },
        { name: '已接单', icon: 'checkbox-filled', status: 1 },
        { name: '配送中', icon: 'paperplane', status: 2 },
        { name: '已完成', icon: 'checkmarkempty', status: 3 }
      ],
      allOrders: [],
      courierId: 3 // 配送员ID，实际项目中可以从登录信息中获取
    }
  },
  computed: {
    filteredOrders() {
      return this.allOrders.filter(order => order.status === this.activeStatus);
    }
  },
  methods: {
    async fetchOrders() {
      try {
        uni.showLoading({ title: '加载中...' });
        
        // 获取待接单订单
        const pendingRes = await uni.request({
          url: 'http://localhost:9090/order/pendingOrders',
          method: 'GET'
        });
        
        // 获取配送员自己的订单
        const courierRes = await uni.request({
          url: `http://localhost:9090/order/courierOrders?courierId=${this.courierId}`,
          method: 'GET'
        });
        
        // 合并订单并去重
        const pendingOrders = pendingRes.data.data || [];
        const courierOrders = courierRes.data.data|| [];
        // 合并并去重
        const allOrdersMap = {};
        [...pendingOrders, ...courierOrders].forEach(order => {
          allOrdersMap[order.id] = order;
        });
        console.log(pendingOrders)
        this.allOrders = Object.values(allOrdersMap);
        
        uni.hideLoading();
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        });
        console.error('获取订单失败:', error);
      }
    },
    getStatusTitle(status) {
      const titleMap = {
        0: '待接单',
        1: '已接单',
        2: '配送中',
        3: '已完成'
      };
      return titleMap[status] || '';
    },
    getStatusText(status) {
      const statusMap = {
        0: '待接单',
        1: '已接单',
        2: '配送中',
        3: '已完成'
      };
      return statusMap[status] || '未知状态';
    },
    getStatusColor(status) {
      switch(status) {
        case 0: return '#FF9800';
        case 1: return '#2196F3';
        case 2: return '#FFC107';
        case 3: return '#4CAF50';
        default: return '#666';
      }
    },
    getStatusBgColor(status) {
      const bgMap = {
        0: 'rgba(255, 152, 0, 0.1)',
        1: 'rgba(33, 150, 243, 0.1)',
        2: 'rgba(255, 193, 7, 0.1)',
        3: 'rgba(76, 175, 80, 0.1)'
      };
      return bgMap[status] || 'rgba(0, 0, 0, 0.1)';
    },
    getWaveColor(status) {
      const waveMap = {
        0: 'linear-gradient(90deg, transparent, rgba(255, 152, 0, 0.3), transparent)',
        1: 'linear-gradient(90deg, transparent, rgba(33, 150, 243, 0.3), transparent)',
        2: 'linear-gradient(90deg, transparent, rgba(255, 193, 7, 0.3), transparent)',
        3: 'linear-gradient(90deg, transparent, rgba(76, 175, 80, 0.3), transparent)'
      };
      return waveMap[status] || 'linear-gradient(90deg, transparent, rgba(0, 0, 0, 0.3), transparent)';
    },
    getOrderCount(status) {
      return this.allOrders.filter(order => order.status === status).length;
    },
    formatTime(timeStr) {
      if (!timeStr) return '';
      const date = new Date(timeStr);
      return `${date.getMonth()+1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    switchStatus(status) {
      this.activeStatus = status;
      this.playSwitchAnimation();
    },
    playSwitchAnimation() {
      // 切换动画效果
      const tabs = document.querySelectorAll('.tab-item');
      tabs.forEach((tab, index) => {
        tab.style.transform = 'scale(0.95)';
        setTimeout(() => {
          tab.style.transform = 'scale(1)';
        }, 300 + index * 100);
      });
    },
    onRefresh() {
      this.refreshing = true;
      this.fetchOrders().finally(() => {
        this.refreshing = false;
        uni.showToast({
          title: '刷新成功',
          icon: 'success'
        });
      });
    },
    async acceptOrder(orderId) {
      uni.showLoading({ title: '接单中...' });
      try {
        const res = await uni.request({
          url: `http://localhost:9090/order/accept?orderId=`+orderId+"&courierId="+ this.courierId,
          method: 'POST',
          // data: {
          //   orderId: orderId,
          //   courierId: this.courierId
          // }
        });
        
        if (res.data && res.data.success) {
          // 更新本地订单状态
          const order = this.allOrders.find(o => o.id === orderId);
          if (order) {
            order.status = 1;
            order.courierId = this.courierId;
          }
          
          uni.showToast({
            title: '接单成功',
            icon: 'success'
          });
        } else {
          throw new Error(res.data.message || '接单失败');
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '接单失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    async pickupOrder(orderId,address) {
      uni.showLoading({ title: '确认取件中...' });
      try {
        const res = await uni.request({
          url: `http://localhost:9090/order/updateStatus?orderId=`+orderId+"&status=2&address="+address,
          method: 'POST',
          // data: {
          //   orderId: orderId
          // }
        });
        
        if (res.data && res.data.success) {
          // 更新本地订单状态
          const order = this.allOrders.find(o => o.id === orderId);
          if (order) order.status = 2;
          
          uni.showToast({
            title: '取件成功',
            icon: 'success'
          });
        } else {
          throw new Error(res.data.message || '取件失败');
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '取件失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    async completeOrder(orderId) {
      uni.showLoading({ title: '确认完成中...' });
      try {
        const res = await uni.request({
          url: `http://localhost:9090/order/complete`,
          method: 'POST',
          data: {
            orderId: orderId
          }
        });
        
        if (res.data && res.data.success) {
          // 更新本地订单状态
          const order = this.allOrders.find(o => o.id === orderId);
          if (order) order.status = 3;
          
          uni.showToast({
            title: '订单已完成',
            icon: 'success'
          });
        } else {
          throw new Error(res.data.message || '完成失败');
        }
      } catch (error) {
        uni.showToast({
          title: error.message || '完成失败',
          icon: 'none'
        });
      } finally {
        uni.hideLoading();
      }
    },
    viewOrderDetail(orderId) {
      uni.navigateTo({
        url: `/pages/orderDetail/orderDetail?id=${orderId}`
      });
    },
    scanQRCode() {
      uni.scanCode({
        success: (res) => {
          uni.showToast({
            title: '扫码成功',
            icon: 'success'
          });
          // 处理扫码结果
        }
      });
    },
    goBack() {
      uni.navigateBack();
    }
  },
  onLoad(options) {
    if (options.status) {
      this.activeStatus = parseInt(options.status);
    }
    this.fetchOrders();
  },
  onShow() {
    // 页面显示时刷新数据
    this.fetchOrders();
  }
}
</script>

<style lang="scss" scoped>
/* 原有样式保持不变 */
.order-list-page {
  position: relative;
  width: 100%;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
  overflow: hidden;
}

.particle-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  overflow: hidden;

  .particle {
    position: absolute;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.6);
    filter: blur(1px);
    opacity: 0.8;
    animation: float 15s infinite ease-in-out;

    &.p1 {
      width: 300rpx;
      height: 300rpx;
      top: 10%;
      left: 5%;
      background: rgba(74, 144, 226, 0.2);
      animation-delay: 0s;
    }

    &.p2 {
      width: 250rpx;
      height: 250rpx;
      bottom: 15%;
      right: 5%;
      background: rgba(76, 175, 80, 0.2);
      animation-delay: 5s;
    }

    &.p3 {
      width: 200rpx;
      height: 200rpx;
      top: 50%;
      left: 20%;
      background: rgba(255, 193, 7, 0.2);
      animation-delay: 10s;
    }
  }
}

.nav-bar {
  display: flex;
  align-items: center;
  padding: 60rpx 30rpx 30rpx;
  position: relative;
  z-index: 10;
  background: linear-gradient(135deg, #4a90e2, #6a8ccc);
  box-shadow: 0 10rpx 30rpx rgba(74, 144, 226, 0.3);

  .nav-back {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(10rpx);
    transition: all 0.3s;

    &:active {
      background: rgba(255, 255, 255, 0.3);
    }
  }

  .nav-title {
    flex: 1;
    text-align: center;
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
    text-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
  }

  .nav-placeholder {
    width: 60rpx;
  }
}

.status-tabs {
  display: flex;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10rpx);
  border-radius: 30rpx;
  margin: -30rpx 30rpx 30rpx;
  padding: 20rpx 0;
  box-shadow: 0 15rpx 40rpx rgba(0, 0, 0, 0.1);
  position: relative;
  z-index: 10;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
  animation: fadeInDown 0.5s ease-out;

  .tab-item {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    transition: all 0.3s;

    .tab-icon {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 10rpx;
      transition: all 0.3s;
    }

    text {
      font-size: 26rpx;
      transition: all 0.3s;
    }

    .tab-badge {
      position: absolute;
      top: -10rpx;
      right: 10rpx;
      min-width: 30rpx;
      height: 30rpx;
      border-radius: 15rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20rpx;
      color: #fff;
      padding: 0 8rpx;
      box-shadow: 0 4rpx 15rpx rgba(0, 0, 0, 0.1);
    }

    &.active {
      .tab-icon {
        transform: translateY(-10rpx);
      }
    }
  }
}

.order-container {
  height: calc(100vh - 260rpx);
  padding: 0 30rpx;
  position: relative;
  z-index: 5;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 0;
  animation: fadeIn 0.5s both;

  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 30rpx;
    opacity: 0.8;
  }

  .empty-text {
    font-size: 32rpx;
    color: #666;
    margin-bottom: 15rpx;
  }

  .empty-tip {
    font-size: 26rpx;
    color: #999;
  }
}

.order-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 24rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
  animation: fadeInUp 0.5s both;
  backdrop-filter: blur(10rpx);
  border: 1rpx solid rgba(255, 255, 255, 0.3);
  transition: all 0.3s;

  &:active {
    transform: scale(0.98);
  }

  .order-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 25rpx;

    .order-no {
      font-size: 30rpx;
      font-weight: bold;
      color: #333;
    }

    .order-status {
      padding: 6rpx 20rpx;
      border-radius: 20rpx;
      font-size: 26rpx;
      font-weight: bold;
    }
  }

  .order-content {
    .info-row {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      &:last-child {
        margin-bottom: 0;
      }

      uni-icons {
        margin-right: 15rpx;
      }

      .info-text {
        font-size: 28rpx;
        color: #666;
      }
    }
  }

  .order-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 30rpx;
    padding-top: 20rpx;
    border-top: 1rpx solid rgba(0, 0, 0, 0.05);

    .order-price {
      font-size: 32rpx;
      font-weight: bold;
      color: #FF9800;
    }

    .order-actions {
      .action-btn {
        height: 60rpx;
        line-height: 60rpx;
        padding: 0 30rpx;
        border-radius: 30rpx;
        font-size: 28rpx;
        color: #fff;
        border: none;
        box-shadow: 0 5rpx 15rpx rgba(0, 0, 0, 0.1);
        transition: all 0.3s;

        &:active {
          transform: scale(0.95);
        }
      }
    }
  }

  .order-wave {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 8rpx;
    animation: wave 3s infinite linear;
  }
}

.float-btn {
  position: fixed;
  right: 40rpx;
  bottom: 40rpx;
  width: 100rpx;
  height: 100rpx;
  background: linear-gradient(135deg, #4a90e2, #6a8ccc);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 15rpx 40rpx rgba(74, 144, 226, 0.4);
  z-index: 100;
  transition: all 0.3s;

  &:active {
    transform: scale(0.95);
  }
}

@keyframes float {
  0%, 100% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(20rpx, -30rpx) rotate(5deg);
  }
  50% {
    transform: translate(-15rpx, 20rpx) rotate(-5deg);
  }
  75% {
    transform: translate(10rpx, -10rpx) rotate(3deg);
  }
}

@keyframes wave {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(50rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-50rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>